// pages/record/sport-list.js
const { get } = require('../../utils/request');

Page({

    /**
     * 页面的初始数据
     */
    data: {
        startDate: '',
        endDate: '',
        records: [],
        totalCount: 0,
        totalDuration: 0,
        totalCalories: 0,
        page: 1,
        pageSize: 10,
        hasMore: true,
        isLoading: false
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        // 默认显示最近一个月的记录
        const end = new Date();
        const start = new Date();
        start.setMonth(start.getMonth() - 1);

        this.setData({
            endDate: this.formatDate(end),
            startDate: this.formatDate(start)
        });

        this.loadRecords();
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {
        this.setData({
            page: 1,
            records: [],
            hasMore: true
        });
        this.loadRecords().then(() => {
            wx.stopPullDownRefresh();
        });
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {
        this.loadMore();
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },

    // 格式化日期
    formatDate(date) {
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');
        return `${year}-${month}-${day}`;
    },

    // 开始日期变化
    onStartDateChange(e) {
        this.setData({
            startDate: e.detail.value,
            page: 1,
            records: [],
            hasMore: true
        });
        this.loadRecords();
    },

    // 结束日期变化
    onEndDateChange(e) {
        this.setData({
            endDate: e.detail.value,
            page: 1,
            records: [],
            hasMore: true
        });
        this.loadRecords();
    },

    // 加载记录
    async loadRecords() {
        if (this.data.isLoading || !this.data.hasMore) return;

        try {
            this.setData({ isLoading: true });

            const { startDate, endDate, page, pageSize } = this.data;
            const res = await get('/records/sport', {
                startDate,
                endDate,
                page,
                pageSize
            });

            // 更新记录列表
            const newRecords = page === 1 ? res.records : [...this.data.records, ...res.records];
            
            // 计算统计数据
            const totalCount = newRecords.length;
            const totalDuration = newRecords.reduce((sum, record) => sum + record.duration, 0);
            const totalCalories = newRecords.reduce((sum, record) => sum + record.calories, 0);

            this.setData({
                records: newRecords,
                totalCount,
                totalDuration,
                totalCalories: totalCalories.toFixed(2),
                hasMore: res.records.length === pageSize,
                page: page + 1
            });
        } catch (error) {
            wx.showToast({
                title: '加载失败',
                icon: 'none'
            });
        } finally {
            this.setData({ isLoading: false });
        }
    },

    // 加载更多
    loadMore() {
        this.loadRecords();
    }
})